import HandleBtn from '@/components/HandleBar/btn';
import DownloadBtn, { downloadFile } from '@/components/HandleBar/downloadBtn';
import type { ActionType, ProColumns, ProFormInstance } from '@/components/Pro/';
import { ModalForm, ProFormDigit, ProFormSelect, ProTable } from '@/components/Pro/';
import {
  reportControllerGetConfig as getReportConfig,
  reportControllerGetReportList as getList,
  reportControllerSaveConfig as saveConfig,
} from '@/services/ess/diagnosisReport';
import { ConfigProvider, Flex, message, Space } from 'antd';
import React, { useRef, useState } from 'react';
import { getLocale, useIntl, useModel } from 'umi';
import Styles from './index.less';

const TYPE = 1; // 电池报告

type ReportProps = {
  id?: number;
  stationId?: number;
  createType?: number;
  stationName?: string;
  createTime?: string;
};

type SearchParamsProps = {
  stationId: string | number;
  ids: (string | number)[];
  fileType: string;
};

const TableList: React.FC = () => {
  const { stationId } = useModel('@@initialState')?.initialState || {};
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);
  const intl = useIntl();
  console.log('intl', intl.locale);
  console.log('getLocale', getLocale());

  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  const configFormRef = useRef<ProFormInstance>();
  const [selectedRowsState, setSelectedRows] = useState<ReportProps[]>([]);
  const [configData, setConfigData] = useState<API.ReportConfigReq>({});

  const download = (fileType: string) => {
    if (!selectedRowsState.length) {
      message.warning(intl.formatMessage({ id: 'global.leastOne' }));
      return;
    }

    const searchParams: SearchParamsProps = {
      stationId,
      ids: selectedRowsState.map((item) => item.id),
      fileType,
    };

    downloadFile(
      `/api/web/diagnosis/report/batch/download?${new URLSearchParams(searchParams).toString()}`,
    );
  };

  const columns: ProColumns<ReportProps>[] = [
    {
      title: intl.formatMessage({ id: 'diagnosticPrediction.reportAnalysis.sn' }),
      dataIndex: 'pageIndex',
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({ id: 'diagnosticPrediction.reportAnalysis.reportName' }),
      dataIndex: 'name',
      width: 180,
    },
    {
      title: intl.formatMessage({ id: 'diagnosticPrediction.reportAnalysis.generationMethod' }),
      dataIndex: 'createType',
      hideInSearch: true,
      valueEnum: {
        1: {
          text: intl.formatMessage({ id: 'global.manual' }),
        },
        0: {
          text: intl.formatMessage({ id: 'global.auto' }),
        },
      },
    },
    {
      title: intl.formatMessage({ id: 'diagnosticPrediction.reportAnalysis.powerPlantName' }),
      dataIndex: 'stationName',
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({ id: 'diagnosticPrediction.reportAnalysis.generationTime' }),
      dataIndex: 'createTime',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'diagnosticPrediction.reportAnalysis.generationTime' }),
      dataIndex: 'createTime',
      valueType: 'dateRange',
      search: {
        transform: (value) => {
          return {
            startDate: value[0],
            endDate: value[1],
          };
        },
      },
      hideInTable: true,
    },
    {
      title: intl.formatMessage({ id: 'diagnosticPrediction.reportAnalysis.operation' }),
      dataIndex: 'option',
      valueType: 'option',
      width: 240,
      render: (_, record) =>
        record?.reportStatus === 1 && (
          <Space>
            <DownloadBtn
              key="view"
              onClick={() => {
                downloadFile(
                  `/api/web/diagnosis/report/view?stationId=${stationId}&id=${record.id}`,
                );
              }}
            >
              {intl.formatMessage({ id: 'diagnosticPrediction.reportAnalysis.view' })}
            </DownloadBtn>
            <DownloadBtn
              key="download1"
              onClick={() => {
                downloadFile(
                  `/api/web/diagnosis/report/download?stationId=${stationId}&id=${record.id}&fileType=pdf`,
                );
              }}
            >
              {intl.formatMessage({ id: 'remoteUpgradeMangment.generalProcedure.download' })}(pdf)
            </DownloadBtn>
            <DownloadBtn
              key="download2"
              onClick={() => {
                downloadFile(
                  `/api/web/diagnosis/report/download?stationId=${stationId}&id=${record.id}&fileType=word`,
                );
              }}
            >
              {intl.formatMessage({ id: 'remoteUpgradeMangment.generalProcedure.download' })}(word)
            </DownloadBtn>
          </Space>
        ),
    },
  ];

  const [automaticGenerationTime1, automaticGenerationTime2, automaticGenerationTime3] = intl
    .formatMessage({
      id: 'diagnosticPrediction.reportAnalysis.reportConfiguration.automaticGenerationTime',
    })
    .split('&--&');

  const [currentConsistencyThreshold1, currentConsistencyThreshold2, currentConsistencyThreshold3] =
    intl
      .formatMessage({
        id: 'diagnosticPrediction.reportAnalysis.reportConfiguration.currentConsistencyThreshold',
      })
      .split('&--&');

  const [lifeAssessmentThreshold1, lifeAssessmentThreshold2, lifeAssessmentThreshold3] = intl
    .formatMessage({
      id: 'diagnosticPrediction.reportAnalysis.reportConfiguration.lifeAssessmentThreshold',
    })
    .split('&--&');
  return (
    <div>
      <ProTable<ReportProps, API.PageParams>
        headerTitle={intl.formatMessage({
          id: 'diagnosticPrediction.reportAnalysis.reportAnalysis',
        })}
        actionRef={actionRef}
        formRef={formRef}
        sticky={{ offsetHeader: 60 }}
        rowKey="id"
        toolBarRender={() => [
          <HandleBtn
            handleType="parameter"
            key="parameter"
            onClick={async () => {
              handleModalOpen(true);
              const res = await getReportConfig({ stationId, type: TYPE });
              if (res) {
                configFormRef?.current?.setFieldsValue(res.data);
                setConfigData(res.data);
              }
            }}
          >
            {intl.formatMessage({ id: 'diagnosticPrediction.reportAnalysis.parameterSettings' })}
          </HandleBtn>,
          <DownloadBtn onClick={() => download('word')} key="export">
            <HandleBtn handleType="download" key="export">
              {intl.formatMessage({ id: 'remoteUpgradeMangment.generalProcedure.batchDownload' })}
              (word)
            </HandleBtn>
          </DownloadBtn>,
          <DownloadBtn onClick={() => download('pdf')} key="export2">
            <HandleBtn handleType="download" key="export">
              {intl.formatMessage({ id: 'remoteUpgradeMangment.generalProcedure.batchDownload' })}
              (pdf)
            </HandleBtn>
          </DownloadBtn>,
        ]}
        toolbar={{
          settings: [],
        }}
        request={getList}
        params={{
          stationId,
          type: TYPE,
        }}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
          getCheckboxProps: (record) => ({
            disabled: record?.reportStatus !== 1,
          }),
        }}
      />
      <ConfigProvider
        theme={{
          token: {
            controlHeight: 32,
          },
          components: {
            InputNumber: {
              paddingBlock: 5,
            },
            Select: {
              controlHeight: 32,
            },
          },
        }}
      >
        <ModalForm
          formRef={configFormRef}
          modalProps={{
            destroyOnClose: true,
          }}
          title={intl.formatMessage({
            id: 'diagnosticPrediction.reportAnalysis.reportConfiguration.automaticGenerationParameter',
          })}
          width="1000px"
          style={{
            marginRight: 0,
          }}
          layout="inline"
          grid={false}
          open={createModalOpen}
          onOpenChange={handleModalOpen}
          submitter={{
            searchConfig: {
              submitText: intl.formatMessage({
                id: 'diagnosticPrediction.reportAnalysis.reportConfiguration.update',
              }),
              resetText: intl.formatMessage({
                id: 'siteManage.cancel',
              }),
            },
          }}
          onFinish={async (value) => {
            try {
              await saveConfig({
                id: configData.id,
                ...value,
                type: TYPE,
                stationId,
              });
              // TODO 翻译
              message.success(intl.formatMessage({ id: 'global.modifiedSuccess' }));
              actionRef?.current?.reload();
              return true;
            } catch (error) {
              // TODO 翻译
              message.error(intl.formatMessage({ id: 'global.editFailedTips' }));
              return false;
            }
          }}
        >
          <Flex className={Styles.configItem} key="1">
            <span className={Styles.configLabel}>{automaticGenerationTime1}</span>
            {automaticGenerationTime2}&nbsp;&nbsp;
            <ProFormSelect
              name="dayOfMonth"
              options={[...new Array(31)].map((_, index) => {
                return {
                  label: index + 1,
                  value: index + 1,
                };
              })}
              width={80}
              disabled={true}
            />
            {automaticGenerationTime3}
          </Flex>
          <Flex className={Styles.configItem} key="2">
            <span className={Styles.configLabel}>{currentConsistencyThreshold1}</span>
            {currentConsistencyThreshold2}&nbsp;&nbsp;
            <ProFormDigit
              name="curThreshold"
              width={80}
              min={1}
              max={100}
              rules={[
                {
                  required: true,
                  message: intl.formatMessage({
                    id: 'diagnosticPrediction.reportAnalysis.reportConfiguration.curThresholdRequired',
                  }),
                },
              ]}
            />
            {currentConsistencyThreshold3}
          </Flex>
          <Flex className={Styles.configItem} key="3">
            <span className={Styles.configLabel}>{lifeAssessmentThreshold1}</span>
            {lifeAssessmentThreshold2}&nbsp;&nbsp;
            <ProFormDigit name="sohThreshold" width={80} disabled={true} />
            {lifeAssessmentThreshold3}
          </Flex>
          <Flex className={Styles.configItem} key="4">
            <span className={Styles.configLabel}>
              {intl.formatMessage({
                id: 'diagnosticPrediction.reportAnalysis.reportConfiguration.socConsistencyEvaluation.label',
              })}
            </span>
            <div>
              <Flex className={Styles.configItem} key="41">
                {intl.formatMessage(
                  {
                    id: 'diagnosticPrediction.reportAnalysis.reportConfiguration.socConsistencyEvaluationT1',
                  },
                  {
                    threshold: (
                      <span style={{ marginLeft: '10px', display: 'inline-block' }}>
                        <ProFormDigit
                          name="socAvgThreshold"
                          width={80}
                          min={1}
                          max={100}
                          rules={[
                            {
                              required: true,
                              message: intl.formatMessage({
                                id: 'diagnosticPrediction.reportAnalysis.reportConfiguration.socAvgThresholdRequired',
                              }),
                            },
                          ]}
                        />
                      </span>
                    ),
                  },
                )}
              </Flex>
              <Flex className={Styles.configItem} key="42">
                {intl.formatMessage(
                  {
                    id: 'diagnosticPrediction.reportAnalysis.reportConfiguration.socConsistencyEvaluationT2',
                  },
                  {
                    threshold: (
                      <span style={{ marginLeft: '10px', display: 'inline-block' }}>
                        <ProFormDigit
                          name="socCheckThreshold"
                          width={80}
                          min={1}
                          max={100}
                          rules={[
                            {
                              required: true,
                              message: intl.formatMessage({
                                id: 'diagnosticPrediction.reportAnalysis.reportConfiguration.socCheckThresholdRequired',
                              }),
                            },
                          ]}
                        />
                      </span>
                    ),
                  },
                )}
              </Flex>
            </div>
          </Flex>
        </ModalForm>
      </ConfigProvider>
    </div>
  );
};
export default TableList;
